#include "ColorParser.h"

#include "IntParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

ColorParser::ColorParser(
    IntParser *&_rParser
    , IntParser *&_gParser
    , IntParser *&_bParser
):    m_rParser(_rParser)
    , m_gParser(_gParser)
    , m_bParser(_bParser)
{

}

bool ColorParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Color());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("r")))
    {
        data = reader->attributes().value(QStringLiteral("r"));
        if (!m_rParser->parse(reader, data))
            return false;
        m_result->r = m_rParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("r: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("g")))
    {
        data = reader->attributes().value(QStringLiteral("g"));
        if (!m_gParser->parse(reader, data))
            return false;
        m_result->g = m_gParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("g: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("b")))
    {
        data = reader->attributes().value(QStringLiteral("b"));
        if (!m_bParser->parse(reader, data))
            return false;
        m_result->b = m_bParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("b: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Color *ColorParser::result()
{
    return m_result.take();
}

}